require "yaml"

puts "This will destroy a unit test and should not be done unless you know what you are doing!!!!"
exit unless(/y/ =~ gets)

ProbeData 	= Struct.new(:name, :gene, :loc, :val)
GeneData 	= Struct.new(:gene_name, :sys_name, :description, :loc, :probes)
LocData		= Struct.new(:chrom, :start, :end)


def gen_probe_names(num)
	p_names = []
	0.upto(num - 1) do |i|
		p_names << "A_00_P000#{i}"
	end

	p_names
end

def gen_names(num)
	gs = []
	0.upto(num - 1) do |i|
		gs << GeneData.new("gene#{i}", "NM_000#{i}", "Gene Descript. #{i}")
	end
	gs
end

PROBE_COUNT = 20

PROBE_NAMES = gen_probe_names(PROBE_COUNT)

GENES 		= gen_names( rand(PROBE_COUNT / 2) + 1 )
# Initialize the genes
GENE_DAT		= GENES.map do |g|
	start 	= rand(200)
	endl 		= rand(200) + start + 100
	locs 		= ((rand(2) == 0) ? [start, endl] : [endl, start]) 
	GeneData.new(g[0], g[1], g[2], LocData.new(-1, locs[0], locs[1]), [])
end

# Initialize the probes
PROBES = PROBE_NAMES.map do |pn|
	probe 	= ProbeData.new(pn, GENE_DAT[rand(GENE_DAT.size)])
	probe.gene.probes << probe

	range		= (probe.gene.loc.start - probe.gene.loc.end).abs
	lower		= [probe.gene.loc.start, probe.gene.loc.end].min
	start		= rand(range) + lower
	p_range	= 20
	forward	= probe.gene.loc.start < probe.gene.loc.end
	endl		= start + (rand(p_range) - (forward ? 0 : p_range))

	probe.loc	= LocData.new(rand(10), start, endl)
	probe.val	= rand - 0.5
	probe
end

## Write out the structures
puts "Writing YAML files"
File.open("test_data/probes.yaml", 'w') {|f| f.write(PROBES.to_yaml)}
File.open("test_data/genes.yaml", 'w') {|f| f.write(GENES.to_yaml)}

## Write out all of the files
# Main data file
puts "Writing data files"
f = File.open("US_test.txt", 'w')
f.write("ProbeName\tGeneName\tSystematicName\tDescription\tLogRatio\n")
PROBES.each do |p| 
	pd = [p.name, p.gene.gene_name, p.gene.sys_name, p.gene.description, p.val]
	f.write(pd.join("\t") + "\n")
end
f.close

f = File.open("lib/data/probe_chrom.txt", 'w')
f.write("ProbeID\tGenomicCoordinates\n")
PROBES.each do |p|
	loc = "chr#{p.loc.chrom}:#{p.loc.start}-#{p.loc.end}"
	f.write([p.name, loc].join("\t") + "\n")
end
f.close

f = File.open("lib/data/gene_loc.txt", 'w')
f.write("RefSeq DNA ID\tGene Start (bp)\tGene End (bp)\tStrand\n")
GENE_DAT.each do |g|
	gloc = [g.loc.start, g.loc.end].sort
	strand = ((g.loc.start < g.loc.end) ? 1 : -1)
	f.write([g.sys_name, gloc[0], gloc[1], strand].join("\t") + "\n")
end
f.close
